package com.initialize.core.security.filter;


import com.initialize.common.tool.jwt.JwtTokenTool;
import com.initialize.core.security.service.UserService;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * User: jane
 * Date: 2020/1/5
 * Time: 5:12 下午
 * token的过滤器.
 * 解析请求头中的token->解析token得到用户信息->丢到SecurityContextHolder中
 *
 * 2020年01月09日23:07:56  此处注释掉@Component的原因: 加上这个注解会造成拦截两次的问题
 * 可以在44行加入 ' log.info("authHeader->>    {}",authHeader);' 自行测试
 */
@Slf4j
//@Component
public class BaseJwtAuthenticationTokenFilter extends OncePerRequestFilter {

    UserService userService;

    public BaseJwtAuthenticationTokenFilter(UserService userService) {
        this.userService = userService;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        String authHeader = request.getHeader("token");

        String requestURI = request.getRequestURI();
        log.info("requestURI-->>  {}",requestURI);
        if (authHeader != null) {
            Claims claimsFromToken = JwtTokenTool.getClaimsFromToken(authHeader);
            String username = claimsFromToken.get("login", String.class);
            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                UserDetails userDetails = userService.loadUserByUsername(username);
                if (userDetails != null) {
                    UsernamePasswordAuthenticationToken authentication =
                            new UsernamePasswordAuthenticationToken(
                                    userDetails,
                                    userDetails.getPassword(),
                                    userDetails.getAuthorities()
                            );
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            }
        }
        chain.doFilter(request, response);
    }
}